
import 'dart:convert';
import 'dart:io';

import 'package:dark_notes/models/notemodel.dart';
import 'package:dark_notes/models/settingsmodel.dart';
import 'package:path_provider/path_provider.dart';

class NoteStorage{
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/notes.json');
  }

  Future<List<Note>> readNotes() async {
    final file = await _localFile;

    try {
      String contents = await file.readAsString();
      var parsedJson = json.decode(contents);
      List<Note> notes = [];
      parsedJson.forEach((note) {
        Note newNote = Note.fromJson(note);
        notes.add(newNote);
      });
      return notes;
    } catch(e) {
      return <Note>[];
    }
  }

  Future<File> writeNotes(List<Note> notes) async {
    final file = await _localFile;
    return file.writeAsString(json.encode(notes));
  }
}

class SettingsStorage{
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/settings.json');
  }

  Future<Settings> readSettings() async {
    final file = await _localFile;

    try {
      String contents = await file.readAsString();
      var parsedJson = json.decode(contents);
      return Settings.fromJson(parsedJson);
    } catch(e) {
      return Settings();
    }
  }

  Future<File> writeSettings(Settings settings) async {
    final file = await _localFile;
    return file.writeAsString(json.encode(settings));
  }
}